package com.coldchain.cys.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coldchain.common.auth.AuthUser;
import com.coldchain.common.msg.BaseResponse;
import com.coldchain.common.msg.ObjectRestResponse;
import com.coldchain.common.util.MD5Utils;
import com.coldchain.cys.constant.Constant;
import com.coldchain.cys.context.CysContext;
import com.coldchain.cys.entity.Cys;
import com.coldchain.cys.entity.CysChild;
import com.coldchain.cys.mapper.CysMapper;
import com.coldchain.cys.page.CysQueryVo;
import com.coldchain.cys.service.ICarDriverService;
import com.coldchain.cys.service.ICarService;
import com.coldchain.cys.service.ICysChildService;
import com.coldchain.cys.service.ICysService;
import com.fangliai.core.context.BaseContextHandler;
import com.fangliai.core.entitiy.SystemModelEnum;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tianpeng
 * @since 2018-08-28
 */
@Service
public class CysServiceImpl extends ServiceImpl<CysMapper, Cys> implements ICysService {

	@Autowired
	private ICysChildService cysChildService ;
	
	@Autowired
	private ICarService carService ;
	
	@Autowired
	private ICarDriverService carDriverService ;
	
//	@Autowired
//	private BizDispatchingOrderFeign bizDispatchingOrderFeign ;
	
	@Override
	public Cys getCysDetail(Long id) {
		return super.getById(id) ;
	}

	@Override
	public Cys getCurrent() {
		Long cysId = CysContext.getCysID();
		return super.getById(cysId) ;
	}

	@Override
	public BaseResponse validateCysLogin(String username, String password) {
		if(StrUtil.isBlank(username)){
			return getErrorResult("用户名不能为空") ;
		}
		if(StrUtil.isBlank(password)){
			return getErrorResult("密码不能为空 ") ;
		}
		Cys cys = getByPhone(username);
		CysChild cysChild = cysChildService.getByPhone(username);
		if(cys == null && cysChild == null){
			return getErrorResult("账号或者密码错误") ;
		}
		String enPassword = MD5Utils.getMD5Str(password) ;
		if(cys != null){
			//承运商主账号登录
			String validateResult = validateCys(cys.getId()) ;
			if(StrUtil.isNotBlank(validateResult)){
				return getErrorResult(validateResult) ;
			}
			if(!cys.getPassword().equals(enPassword)){
				return getErrorResult("账号或者密码错误") ;
			}
			AuthUser authUser = new AuthUser();
			authUser.setCysId(cys.getId().toString());
			authUser.setNickName(cys.getName());
			authUser.setSysModel(SystemModelEnum.CYS);
			authUser.setUserId(Constant.CYS_ADMIN_USER_ID);
			return new ObjectRestResponse<AuthUser>().data(authUser) ;
		}else{
			//承运商子账号登录
			String validateResult = cysChildService.validateCysChild(cysChild.getId());
			if(StrUtil.isNotBlank(validateResult)){
				return getErrorResult(validateResult) ;
			}
			if(!cysChild.getPassword().equals(enPassword)){
				return getErrorResult("账号或者密码错误") ;
			}
			
			AuthUser authUser = new AuthUser();
			authUser.setCysId(cysChild.getCid().toString());
			authUser.setSysModel(SystemModelEnum.CYS);
			authUser.setNickName(cysChild.getPhone());
			authUser.setRoles(cysChild.getRoleid().toString());
			authUser.setUserId(cysChild.getId().toString());
			return new ObjectRestResponse<AuthUser>().data(authUser) ;
		}
		
	}
	
	private BaseResponse getErrorResult(String msg){
		return new ObjectRestResponse<AuthUser>().error(msg) ;
	}
	
	@Override
	public Cys getByPhone(String phone){
		QueryWrapper<Cys> ew = new QueryWrapper<Cys>();
		ew.eq("phone", phone) ;
		return super.getOne(ew) ;
	}

	@Transactional
	@Override
	public RestResponse doEditPass(String originalPass, String newPass, String newPass2) {
		String userId = BaseContextHandler.getUserID();
		if(StrUtil.isBlank(userId)){
			return GetRest.getFail("操作失败") ;
		}
		if(StrUtil.isBlank(originalPass)){
			return GetRest.getFail("原始密码不能为空") ;
		}
		if(StrUtil.isBlank(newPass)){
			return GetRest.getFail("新密码不能为空") ;
		}
		if(!StrUtil.equals(newPass, newPass2)){
			return GetRest.getFail("两次密码不一致") ;
		}
		String enOriginalPass = MD5Utils.getMD5Str(originalPass) ;
		String enNewPass = MD5Utils.getMD5Str(newPass) ;
		if(userId.equals(Constant.CYS_ADMIN_USER_ID)){
			//承运商主账号登录
			Long cysId = CysContext.getCysID(); 
			Cys cys = super.getById(cysId);
			String validateResult = validateCys(cys.getId()) ;
			if(StrUtil.isNotBlank(validateResult)){
				return GetRest.getFail(validateResult) ;
			}
			if(!cys.getPassword().equals(enOriginalPass)){
				return GetRest.getFail("原始密码错误") ;
			}
			cys.setPassword(enNewPass);
			super.updateById(cys) ; //更新
		}else{
			//承运商子账号登录
			Long cysChildId = Long.parseLong(userId) ;
			CysChild cysChild = cysChildService.getById(cysChildId);
			String validateResult = cysChildService.validateCysChild(cysChild.getId());
			if(StrUtil.isNotBlank(validateResult)){
				return GetRest.getFail(validateResult) ;
			}
			if(!cysChild.getPassword().equals(enOriginalPass)){
				return GetRest.getFail("原始密码错误") ;
			}
			cysChild.setPassword(enNewPass);
			cysChildService.updateById(cysChild) ;//更新
		}
		
		return GetRest.getSuccess("密码修改成功，下次登录生效") ;
	}

	@Override
	public String validateCys(Long cysid) {
		Cys cys = super.getById(cysid);
		if(cys == null){
			return "承运商不存在" ;
		}
		if(cys.getIsdel() == Constant.LOGIC_DELETE){
			return "当前登录承运商已被删除" ;
		}
		if(cys.getIsuse() == Constant.DISABLE_USE){
			return "当前承运商是禁用状态" ;
		}
		return null;
	}

	@Override
	public CysChild getCurrentLogin() {
		CysChild currentLogin = new CysChild();
		String userId = BaseContextHandler.getUserID();
		if(userId.equals(Constant.CYS_ADMIN_USER_ID)) {
			//承运商主账号
			Cys c = getCurrent();
			currentLogin.setRoleid("-1"); //-1代表超级管理员
			currentLogin.setPhone(c.getPhone()); 
		}else {
			//承运商子账号 
			CysChild cysChild = cysChildService.getById(Long.parseLong(userId));
			currentLogin.setRoleid(cysChild.getRoleid());
			currentLogin.setPhone(cysChild.getPhone());
		}
		
		return currentLogin ; 
	}

	@Override
	public void getList(CysQueryVo vo) {
		QueryWrapper<Cys> ew = new QueryWrapper<Cys>();
		super.page(vo, ew) ;
	}



	@Transactional
	@Override
	public BaseResponse doDeleteCys(Long cysId) {
		if(cysId == null) {
			return getErrorResult("参数错误") ;
		}
		String sysModel = BaseContextHandler.getSysModl();
		if(!sysModel.equals(SystemModelEnum.ADMIN.name())) {
			return getErrorResult("非法操作") ;
		}
		boolean result = super.removeById(cysId);
		if(!result) {
			return getErrorResult("操作失败") ;
		}
		return new ObjectRestResponse<>().succeed("操作成功") ;
	}

	@Transactional
	@Override
	public BaseResponse doSwitchCysUse(Long cysId) {
		if(cysId == null) {
			return getErrorResult("参数错误") ;
		}
		String sysModel = BaseContextHandler.getSysModl();
		if(!sysModel.equals(SystemModelEnum.ADMIN.name())) {
			return getErrorResult("非法操作") ;
		}
		Cys cys = super.getById(cysId);
		if(cys.getIsuse() == Constant.DISABLE_USE) {
			cys.setIsuse(Constant.ENABLE_USE);
		}else {
			cys.setIsuse(Constant.DISABLE_USE);
		}
		boolean result = super.updateById(cys) ;
		if(!result) {
			return getErrorResult("操作失败") ;
		}
		return new ObjectRestResponse<>().succeed("操作成功") ;
	}

	@Transactional
	@Override
	public BaseResponse doAddCys(Cys cys) {
		if(StrUtil.isBlank(cys.getName())) {
			return getErrorResult("承运商名称不能为空") ;
		}
		if(StrUtil.isBlank(cys.getEnterpriseName())) {
			return getErrorResult("企业名称不能为空") ;
		}
		if(StrUtil.isBlank(cys.getArea())) {
			return getErrorResult("地区不能为空") ;
		}
		if(StrUtil.isBlank(cys.getPhone())) {
			return getErrorResult("手机号码不能为空") ;
		}
		if(!Validator.isMobile(cys.getPhone())) {
			return getErrorResult("请填写正确的手机号码") ;
		}
		Cys c = getByPhone(cys.getPhone());
		if(c != null) {
			return getErrorResult("该手机号码已经有承运商存在") ;
		}
		if(cys.getScale() == null) {
			return getErrorResult("拔出佣金比例不能为空") ;
		}
		String md5 = MD5Utils.getMD5Str(Constant.DEFAULT_PASSWORD) ; //默认密码123456
		cys.setPassword(md5);
		boolean result = super.save(cys);
		if(!result) {
			return getErrorResult("操作失败") ;
		}
		
		return new ObjectRestResponse<>().succeed("操作成功") ;
	}


	
}
